# -*- coding: utf-8 -*-
# 创建序列化器
import re

from rest_framework import serializers
from sixstart.models import BookInfo,User

# class BookInfoSerializer(serializers.ModelSerializer):
#     # 图书的数据序列化器
#     class Meta:
#         model =  BookInfo
#         fields = "__all__"
#         # fields = ('id','btitle')


class BookInfoSerializer(serializers.Serializer):
    # 图书的数据序列化器
    id = serializers.IntegerField(label="ID",read_only=True)
    btitle = serializers.CharField(max_length=20, label='名称')
    bpub_date = serializers.DateField(label='发布日期',required=False)
    bread = serializers.IntegerField(label='阅读量',required=False)
    bcomment = serializers.IntegerField( label='评论量',required=False)
    # is_delete = serializers.BooleanField(default=False, label='逻辑删除')

    # 反序列化 validate_<field_name>
    # 对<field_name>字段进行验证，如

    def validate_btitle(self,value):
        print("进来了")
        if 'django' not in value.lower():
            raise serializers.ValidationError("图书不是关于Django的")
        return value

    # validate 在序列化器中需要同时对多个字段进行比较验证时，可以定义validate方法来验证，如
    def validate(self, attrs):
        bread = attrs['bread']
        bcomment = attrs['bcomment']
        if bread < bcomment:
            raise serializers.ValidationError('阅读量小于评论量')
        return attrs

    # 校验
    def update(self, instance, validated_data):
        # 更新数据
        instance.btitle = validated_data.get('btitle',instance.btitle)
        instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date)
        instance.bread = validated_data.get('bread', instance.bread)
        instance.bcomment = validated_data.get('bcomment', instance.bcomment)
        instance.save()
        return instance

    def create(self, validated_data):
        # 新增数据
        book = BookInfo(**validated_data)
        book.save()
        return book


class HeroInfoSerializer(serializers.Serializer):
    # 英雄的序列化
    GENDER_CHOICES = (
        (0,'male'),
        (1,'female')
    )
    id = serializers.IntegerField(label="ID", read_only=True)
    hname = serializers.CharField(max_length=20, label='名称')
    hgender = serializers.ChoiceField(choices=GENDER_CHOICES, default=0, label='性别',required=False)
    hcomment = serializers.CharField(max_length=200,  label='描述信息')
    hbook = serializers.StringRelatedField(label="图书",read_only=True)



class UserSerializer(serializers.ModelSerializer):
    # 用户注册的序列器
    password2 = serializers.CharField(label="重复密码",max_length=16,required=True,write_only=True)
    class Meta:
        model = User
        fields = ("id","mobile","password","password2")

    # def validate_password2(self,attrs):
    #     pass

    def validate_mobile(self,value):
        # 校验逻辑
        # 手机号的正则判断
        if not re.match(r'^1[3-9]\d{9}$',value):
            print(value)
            raise serializers.ValidationError("手机号格式错误")
        return value

    def validate(self, data):
        # 重复输入的密码要一致的判断
        print(data)
        if data["password2"] != data["password"]:
            raise serializers.ValidationError("两次输入密码不一致")
        return data
    # 保存数据
    def create(self,validated_data):
        print(validated_data)
        del validated_data["password2"]
        print(validated_data)
        #user = User.objects.create(mobile=validated_data["mobile"],password=validated_data["password"])
        user = User.objects.create(**validated_data)  # 字典解包
        user.save()
        return user
